package com.dcc.xiangche.support;

import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.dcc.xiangche.domain.NativeProduct;
import com.dcc.xiangche.domain.Product;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class WSXCHandler {

    private String inputDirectory;
    private String jsonFileName;

    private String jsonFilePreName;

    private String outputDirectory;
    private Boolean overwrite;

    public void process(String inputDirectory, String jsonFileName, Boolean overwrite) throws Exception {

        File inputDir = new File(inputDirectory);
        if (!inputDir.exists()) {
            throw new FileNotFoundException("输入目录不存在");
        }
        if (!inputDir.isDirectory()) {
            throw new IOException("输入目录应是一个目录而不应该是文件");
        }
        //json文件路径
        String jsonFilePath = inputDirectory.endsWith(File.separator) ? inputDirectory + jsonFileName : inputDirectory + File.separator + jsonFileName;
        File file = new File(jsonFilePath);
        if (!file.exists())
            throw new FileNotFoundException("输入文件不存在");


        this.inputDirectory = inputDirectory;
        this.jsonFileName = jsonFileName;
        this.overwrite = overwrite;
        this.jsonFilePreName = this.jsonFileName.contains(".") ? jsonFileName.substring(0, jsonFileName.indexOf(".")) : jsonFileName;
        this.outputDirectory = inputDirectory + File.separator + jsonFilePreName+"xlsx";

        //创建产品数据
        List<Product> products = analysisJsonFile(file);
        Map<String, List<Product>> collect = products.stream().collect(Collectors.groupingBy(Product::getCategory));

        File dir = new File(outputDirectory);
        if (dir.exists()) {
            if (!this.overwrite) {
                new FileAlreadyExistsException("目录已经存在[" + outputDirectory + "]");
            }
        }else{
            dir.mkdirs();
        }

        for (Map.Entry<String,List<Product>> entry:collect.entrySet()) {
            writeXlsFile(entry.getKey(),entry.getValue());
        }
    }

    private List<Product> analysisJsonFile(File file) {
        String s = FileUtil.readString(file, Charset.forName("UTF-8"));
        JSONArray objects = JSONUtil.parseArray(s);
        List<NativeProduct> products = JSONUtil.toList(objects, NativeProduct.class);

        //生成笛卡尔集
        ArrayList<Product> result = new ArrayList<>();
        for (NativeProduct p : products) {
            ArrayList<Product> descartesProducts = new ArrayList<>();
            List<String> sizes = p.getSizes();
            List<String> colors = p.getColors();
            for (String size : sizes) {
                for (String color : colors) {
                    Product descartesProduct = new Product();
                    BeanCopier.create(p, descartesProduct, CopyOptions.create().setIgnoreError(true)).copy();
                    descartesProduct.setSize(size);
                    descartesProduct.setColor(color);
                    descartesProducts.add(descartesProduct);
                }
            }
            result.addAll(descartesProducts);
        }
        return result;
    }

    private void writeXlsFile(String category, List<Product> products) throws IOException {
        //生成模板空文件到指定目录
        String outputXlsxFilePath = outputDirectory+File.separator +category+".xlsx";
        File file = new File(outputXlsxFilePath);
        if(!file.exists()){
            file.createNewFile();
        }

        //根据模板文件创建导出文件
        InputStream resourceAsStream = WSXCHandler.class.getResourceAsStream("/template.xlsx");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IoUtil.copy(resourceAsStream,fileOutputStream);
        resourceAsStream.close();
        fileOutputStream.close();

        ExcelReader reader = ExcelUtil.getReader(file);
        ExcelWriter writer=reader.getWriter();

        List<String> codes=new ArrayList<>();

        for (int i = 0; i < products.size(); i++) {
            int currentRow = i + 1;

            Product product = products.get(i);
            //写图片
            if(!codes.contains(product.getCode())) {
                codes.add(product.getCode());
                int imgSize=product.getImages().size()>25 ? 25:product.getImages().size();
                for (int j = 0; j < imgSize; j++) {
                    File imageFile = createImageFile(product.getImages().get(j));
                    if (imageFile != null)
                        writer.writeImg(imageFile, j, currentRow, j + 1, currentRow + 1);
                }
            }
            //描述
            writer.writeCellValue(26, currentRow, product.getName());
            //价格
            writer.writeCellValue(27, currentRow, 1);
            //货号
            writer.writeCellValue(28, currentRow, product.getCode());
            //标签
            writer.writeCellValue(29, currentRow, this.jsonFilePreName + product.getCategory());
            //规格
            writer.writeCellValue(32, currentRow, product.getSize());
            //颜色
            writer.writeCellValue(33, currentRow, product.getColor());
            //库存
            writer.writeCellValue(39, currentRow, randomNum(20, 500));
        }
        writer.flush();
        reader.close();
    }

    private int randomNum(int min, int max) {
        return min + (int) (Math.random() * ((max - min) + 1));
    }

    private File createImageFile(String filePath) {
        File file = new File(inputDirectory + File.separator + filePath);
        if (!file.exists())
            return null;
        return file;
    }
}
